<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>
    </head>
    <body>
		<?php
		/*
		 * This script is used to parse  a xml file about Cis regulatory region
		 * it changes the absolute coordinates from the aniseedDB v3 to the
		 * new absolute cordinates from Edwin Jacox
		 *
		 * Be carefull, in the edwin file's "aniseedCRMs-ghost_nohead.csv"
		 * when the strand orientation is -, begin is higher than the end
		 * so in this parser we put begin at the end and the end at the begin if
		 * strand is -
		 *
		 * 
		 */


		$arrResult = array();
//		$arrLines = file('clustertogene.csv');
		$arrLines = file('aniseedCRMs-ghost_nohead.csv');
		foreach ($arrLines as $line) {
			$tmp = explode(',', $line);
			$arrResult[trim($tmp[1])] =
					array('kh' => trim($tmp[2]),
						'begin' => trim($tmp[3]),
						'end' => trim($tmp[4]),
						'strand' => trim($tmp[5]));
		}

		$dom = new DOMDocument();
		$dom->formatOutput = true;
		$dom->preserveWhiteSpace = false;
		$dom->load('RegulatoryRegions.xml');
		$elts = $dom->getElementsByTagName('analysis');

		$alreadyUsed = array();
		foreach ($elts as $elt) {

			$stable_identifier = $elt->getElementsByTagName('stable_identifier')->item(0);
			$aBegin = $elt->getElementsByTagName('a_begin')->item(0);
			$aEnd = $elt->getElementsByTagName('a_end')->item(0);
			$strand = $elt->getElementsByTagName('strand_orientation')->item(0);
			$contig = $elt->getElementsByTagName('contig')->item(0);
//			$kh = $arrResult[$stable_identifier->nodeValue]['kh'];
//			$kh = strtoupper(substr($kh, 0, 2)) . '.' . strtoupper((substr($kh, 2)));
//			print_r($kh . "<br />");


			if (key_exists(trim($stable_identifier->nodeValue), $arrResult)) {
				if (strcmp($arrResult[$stable_identifier->nodeValue]['strand'], '-') == 0) {
					$aBegin->nodeValue = utf8_encode($arrResult[$stable_identifier->nodeValue]['end']);
					$aEnd->nodeValue = utf8_encode($arrResult[$stable_identifier->nodeValue]['begin']);
					$strand->nodeValue = utf8_encode($arrResult[$stable_identifier->nodeValue]['strand']);
					$contig->nodeValue = utf8_encode($arrResult[$stable_identifier->nodeValue]['kh']);
				} else {
					$aBegin->nodeValue = utf8_encode($arrResult[$stable_identifier->nodeValue]['begin']);
					$aEnd->nodeValue = utf8_encode($arrResult[$stable_identifier->nodeValue]['end']);
					$strand->nodeValue = utf8_encode($arrResult[$stable_identifier->nodeValue]['strand']);
					$contig->nodeValue = utf8_encode($arrResult[$stable_identifier->nodeValue]['kh']);
				}
			} else {
				
			}
		}

                
//		$dom->save('testintegration.xml');
		$dom->save('your xml destination.xml');
		?>
    </body>
</html>
